package logging

import (
	"fmt"
	"time"
	"os"
	"log"
	"go-pipe/api/utilsfile"
)

var (
	LogSavePath    string
	LogSaveName    string
	LogFileExt     string
	timeFormat     string
)

func init() {

	//config := utilsfile.GetConfig(utilsfile.GetFilePath("logfile", "filepath.json"), "filepath.json")
	config := utilsfile.GetConfig("logfile", "filepath.json")
	LogSavePath = config.Get("path").(string)
	timeFormat = config.Get("timeFormat").(string)
	LogSaveName = config.Get("logSaveName").(string)
	LogFileExt = config.Get("logFileExt").(string)

}

func getLogFileFullPath(f string) string {
	prefixPath := LogSavePath
	suffixPath := fmt.Sprintf("%s_%s_%s.%s", f,LogSaveName, time.Now().Format(timeFormat), LogFileExt)

	return fmt.Sprintf("%s%s", prefixPath, suffixPath)
}

func openLogFile(filePath string) *os.File {

	_, err := os.Stat(filePath)
	switch {
	case os.IsNotExist(err):
		mkDir(LogSavePath)

	case os.IsPermission(err):
		log.Fatalf("Permission : %v", err)
	}

	handle, err := os.OpenFile(filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)

	if err != nil {
		log.Fatalf("Fail to OpenFile : %v", err)
	}

	return handle

}

func mkDir(filePath string) {
	dir, _ := os.Getwd()

	err := os.MkdirAll(dir+"/"+LogSavePath, os.ModePerm)

	if err != nil {
		panic(err)
	}
}
